<template>
    <div class="g-dialog-container" v-loading="loading" element-loading-text="加载中"
         element-loading-spinner="el-icon-loading">
        <div class="g-dialog-content">
            <el-form size="mini" label-suffix="：" :model="ruleForm" status-icon :rules="rules" ref="ruleForm"
                     label-width="100px" class="demo-ruleForm">
                <el-form-item label="角色名称" prop="name" style="width: 60%">
                    <el-input show-word-limit maxlength="20" placeholder="请输入" size="mini" v-model="ruleForm.name"
                              clearable></el-input>
                </el-form-item>
                <el-form-item label="备注" style="width: 80%">
                    <el-input
                        type="textarea"
                        :autosize="{ minRows: 8, maxRows: 8 }"
                        :maxlength="255"
                        resize="none"
                        size="mini"
                        placeholder="请输入"
                        v-model="ruleForm.description"
                        show-word-limit
                    ></el-input>
                </el-form-item>
                <el-form-item label="菜单权限" prop="menuIds" style="width: 80%">
                    <ul ref="menuTree">
                        <li v-for="(item) in menuOptions" :key="item.menuId" class="menu-tree">
                            <el-tree
                                :data="[item]"
                                node-key="menuId"
                                :ref="item.menuId"
                                :props="defaultProps"
                                :default-checked-keys="defaultCheckedKeys"
                                :highlight-current="false"
                                @check="getCheckMenuIds"
                                show-checkbox>
                            </el-tree>
                        </li>
                    </ul>
                </el-form-item>
            </el-form>
        </div>
        <div class="g-dialog-footer">
            <el-button type="primary" size="mini" icon="el-icon-circle-check" @click="handleSave">保存</el-button>
            <el-button type="primary" size="mini" icon="el-icon-circle-close" @click="handleCancel">取消</el-button>
        </div>
    </div>
</template>
<script>
// api
import { addRole, getRole, updateRole } from '@/api/system/role'
import { getCommonList } from '@/api/common'
import { deepClone } from '@/utils'

export default {
    props: {
        //判断是否进行修改
        isUpdate: {
            type: Boolean,
            default: true
        },
        // 角色id
        roleId: {
            type: [String, Number],
            default: ''
        }
    },
    data() {
        const validateSourceGroupName = (rule, value, callback) => {
            if (!value) {
                callback(new Error('角色名称不能为空'))
            } else {
                callback()
            }
        }
        return {
            defaultProps: {
                children: 'childMenuList',
                label: 'menuName'
            },
            defaultCheckedKeys: [],
            loading: false,
            ruleForm: {
                id: null,
                name: '',
                description: '',
                menuIds: []
            },
            menuIds: [],
            menuOptions: [],
            rules: {
                name: [
                    {
                        required: true,
                        trigger: 'blur',
                        validator: validateSourceGroupName
                    }
                ],
                menuIds: [
                    {
                        required: true,
                        message: '菜单权限不能为空',
                        trigger: 'blur'
                    }
                ]
            }
        }
    },
    created() {
        this.getData()
    },
    methods: {
        async getData() {
            this.loading = true
            await getCommonList('menu')
                .then(res => {
                    if (res.status !== 200) return this.$msgPrompt.error(res.msg)
                    this.menuOptions = res.obj
                })
                .catch(() => {
                })
            if (!this.isUpdate) return this.loading = false
            this.getRole()
        },
        getRole() {
            getRole(this.roleId).then((res) => {
                if (res.status != 200) return this.$msgPrompt.error(res.msg)
                this.ruleForm.name = res.obj.name
                this.ruleForm.description = res.obj.description
                this.ruleForm.id = res.obj.id
                this.defaultCheckedKeys = res.obj.menuIds
                // 由于返回数据中 返回了根节点Id
                // 删除非仅为叶节点的根节点Id 防止默认选中所有
                this.menuOptions.forEach(item => {
                    this.defaultCheckedKeys.forEach((key, keyIndex) => {
                        if (item.childMenuList && item.childMenuList.length && item.menuId === key) {
                            this.defaultCheckedKeys.splice(keyIndex, 1)
                        }
                    })
                })
                this.menuOptions[0].disabled = true
                this.defaultCheckedKeys = ['Home']
                this.loading = false
            })
        },
        getCheckMenuIds() {
            // 获取菜单dom对象
            let refs = this.menuOptions.map(item => item.menuId)
            // 遍历dom对象获取对应树节点选中
            let checkNodes = []
            refs.forEach(item => {
                let nodes = this.$refs[item][0].getCheckedNodes(false, true)
                // 放入一级 及 二级childrenMenuList
                if (nodes.length) {
                    checkNodes.push(...nodes)
                }
            })
            checkNodes = deepClone(checkNodes)
            // 删除 childMenuList 属性
            for (let i = 0; i < checkNodes.length; i++) {
                console.log(checkNodes[i].childMenuList)
                if (checkNodes[i].childMenuList) {
                    checkNodes.splice(i, 1)
                    i--
                }
            }
            this.defaultCheckedKeys = checkNodes.map(item => item.menuId)
        },
        //保存
        handleSave() {
            // 获取菜单dom对象
            let refs = this.menuOptions.map(item => item.menuId)
            // 遍历dom对象获取对应树节点选中
            let checkNodes = []
            refs.forEach(item => {
                let nodes = this.$refs[item][0].getCheckedNodes(false, true)
                // 放入一级 及 二级childrenMenuList
                if (nodes.length) {
                    checkNodes.push(...nodes)
                }
            })
            checkNodes = deepClone(checkNodes)
            // 删除 包含半选节点的children项 保留父节点
            checkNodes.forEach(item => {
                if (item.childMenuList) {
                    delete item.childMenuList
                }
            })
            this.ruleForm.menuIds = checkNodes.map(item => item.menuId)
            console.log(this.ruleForm)
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.$startLoading()
                    this.isUpdate ? this.roleUpdate() : this.addRole()
                } else {
                    return false
                }
            })
        },
        //添加
        addRole() {
            addRole(this.ruleForm).then((res) => {
                this.$endLoading()
                if (res.status != 200) return this.$msgPrompt.error(res.msg)
                this.$msgPrompt.success()
                this.$emit('succeed')
            })
        },
        //修改
        roleUpdate() {
            updateRole(this.ruleForm).then((res) => {
                this.$endLoading()
                if (res.status != 200) return this.$msgPrompt.error(res.msg)
                this.$msgPrompt.success()
                this.$emit('succeed')
            })
        },
        //取消
        handleCancel() {
            this.$emit('close')
        }
    }
}
</script>
<style scoped lang="scss">
.g-dialog-container {
    position: relative;
    width: 100%;
    height: 100%;

    .shade-text {
        display: flex;
        align-items: center;
        margin-bottom: 20px;

        ::v-deep.el-form-item {
            margin-bottom: 0;
        }
    }

    .el-checkbox-group {
        display: flex;
        flex-display: row;
        flex-wrap: wrap;

        .el-checkbox {
            min-width: 100px;
        }
    }


    .el-input,
    .el-select {
        width: 230px;
    }

    .el-textarea {
        width: 562px;
    }

    ul {

        width: 562px;
        height: 190px;
        overflow: auto;

    }

    .menu-tree {
        display: inline-block;
        vertical-align: top;
        width: 270px;

        ::v-deep .el-tree {
            .el-tree-node {
                &:focus > .el-tree-node__content {
                    background-color: transparent;
                }
            }

            .el-tree-node__content {
                &:hover {
                    background-color: transparent;
                }
            }
        }
    }
}
</style>
